package com.lagou.edu.factory;

import com.lagou.edu.annotion.Autowired;
import com.lagou.edu.annotion.Service;
import com.lagou.edu.annotion.Transactional;
import com.lagou.edu.utils.ScanUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;

/**
 * @author 应癫
 * <p>
 * 工厂类，生产对象（使用反射技术）
 */
public class BeanFactory {

    /**
     * 任务一：读取解析xml，通过反射技术实例化对象并且存储待用（map集合）
     * 任务二：对外提供获取实例对象的接口（根据id获取）
     */

    private static Map<String, Object> singleObjects = new HashMap<>();  // 存储对象
    private static Map<Class, Object> typeSingleObjects = new HashMap<>();  // 存储类型对象映射
    private static Map<Class, Object> proxyObjects = new HashMap<>();  // 存储代理对象


    static {
        // 任务一：读取解析xml，通过反射技术实例化对象并且存储待用（map集合）
        // 加载xml
        InputStream resourceAsStream = BeanFactory.class.getClassLoader().getResourceAsStream("beans.xml");
        // 1.解析xml bean
        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();
            List<Element> beanList = rootElement.selectNodes("//bean");
            for (int i = 0; i < beanList.size(); i++) {
                Element element = beanList.get(i);
                // 处理每个bean元素，获取到该元素的id 和 class 属性
                String id = element.attributeValue("id");        // accountDao
                String clazz = element.attributeValue("class");  // com.lagou.edu.dao.impl.JdbcAccountDaoImpl
                // 通过反射技术实例化对象
                Class<?> aClass = Class.forName(clazz);
                Object o = aClass.newInstance();  // 实例化之后的对象

                // 存储到map中待用
                singleObjects.putIfAbsent(id, o);
                for (Class<?> interfacez : aClass.getInterfaces()) {
                    typeSingleObjects.putIfAbsent(interfacez, o);
                }
                typeSingleObjects.putIfAbsent(aClass, o);
            }

            //2.扫描包下所有类注解
            Set<Class<?>> classes = null;
            List<Element> list = rootElement.selectNodes("//component-scan");
            if (!list.isEmpty()) {
                String basePackage = list.iterator().next().attributeValue("base-package");
                classes = componentScanClass(basePackage);
            }

            // 3.实例化完成之后维护对象的依赖关系，检查哪些对象需要传值进入，根据它的配置，我们传入相应的值
            // 有property子元素的bean就有传值需求
            List<Element> propertyList = rootElement.selectNodes("//property");
            // 解析property，获取父元素
            for (int i = 0; i < propertyList.size(); i++) {
                Element element = propertyList.get(i);   //<property name="AccountDao" ref="accountDao"></property>
                String name = element.attributeValue("name");
                String ref = element.attributeValue("ref");

                // 找到当前需要被处理依赖关系的bean
                Element parent = element.getParent();

                // 调用父元素对象的反射功能
                String parentId = parent.attributeValue("id");
                Object parentObject = singleObjects.get(parentId);
                // 遍历父对象中的所有方法，找到"set" + name
                Method[] methods = parentObject.getClass().getMethods();
                for (int j = 0; j < methods.length; j++) {
                    Method method = methods[j];
                    if (method.getName().equalsIgnoreCase("set" + name)) {  // 该方法就是 setAccountDao(AccountDao accountDao)
                        method.invoke(parentObject, singleObjects.get(ref));
                    }
                }

                // 把处理之后的parentObject重新放到map中
                singleObjects.put(parentId, parentObject);
            }

            //4.扫描包下所有属性注解
            componentScanProperty();

        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

    }

    private static Object doCreateBean(Class clazz) throws IllegalAccessException, InstantiationException {
        if (clazz.getAnnotation(Transactional.class) == null) {
            Method[] methods = clazz.getDeclaredMethods();
            boolean hasTransaction = false;
            for (Method method : methods) {
                if (method.getAnnotation(Transactional.class) != null) {
                    hasTransaction = true;
                    break;
                }
            }
            if (!hasTransaction) {
                return clazz.newInstance();
            }
        }
        //扫描后执行 ProxyFactory已通过xml注入容器，不为null
        ProxyFactory proxyFactory = getBean(ProxyFactory.class);
        Object sourceBean = clazz.newInstance();
        Object proxyBean = proxyFactory.getCglibProxy(sourceBean);
        for (Class<?> interfacez : clazz.getInterfaces()) {
            proxyObjects.putIfAbsent(interfacez, proxyBean);
        }
        proxyObjects.putIfAbsent(clazz, proxyBean);
        return sourceBean;
    }

    private static void componentScanProperty() {
        singleObjects.entrySet().forEach(entry -> {
            Object bean = entry.getValue();
            Field[] fields = bean.getClass().getDeclaredFields();
            for (Field field : fields) {
                if (field.getAnnotation(Autowired.class) != null) {
                    try {
                        Object populateBean = typeSingleObjects.get(field.getType());
                        field.setAccessible(true);
                        field.set(bean, populateBean);
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    private static Set<Class<?>> componentScanClass(String basePackage) {
        Set<Class<?>> classes = ScanUtils.getClassSet(basePackage);
        classes.forEach(clazz -> {
            try {
                Service annotation = clazz.getAnnotation(Service.class);
                if (annotation != null) {
                    Object singleObject = doCreateBean(clazz);
                    singleObjects.putIfAbsent(annotation.name() != null && !"".equals(annotation.name().trim()) ? annotation.name() : clazz.getName().substring(clazz.getName().lastIndexOf(".") + 1), singleObject);
                    for (Class<?> interfacez : clazz.getInterfaces()) {
                        typeSingleObjects.putIfAbsent(interfacez, singleObject);
                    }
                    typeSingleObjects.putIfAbsent(clazz, singleObject);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        return classes;
    }

    // 任务二：对外提供获取实例对象的接口（根据id获取）
    public static Object getBean(String id) {
        return singleObjects.get(id);
    }

    public static <T> T getBean(Class<T> clazz) {
        Object bean = proxyObjects.get(clazz);
        if (bean != null) {
            return (T) bean;
        }
        return (T) typeSingleObjects.get(clazz);
    }

}
